#include "udp.h"
#include "mainwindow.h"
#include <cmath>
#include <QDebug>
#define PI 3.1415927
//UdpClient::UdpClient(MainWindow *parent)
UdpClient::UdpClient()
{
 //   this->parent = parent;

    init();

    m_bRead=false;

    udpSocket=0;
    port = 1999;
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(port);
    connect(udpSocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));

//    qDebug()<<sizeof(ETC_S)<<" "<<sizeof(ETC_D)<<" "<<sizeof(unsigned short)<<" "<<sizeof(double);
}
void UdpClient::init()
{
    rms_tmp=0;
    freq_tmp=0;
    phase_tmp=0;

    isFt3 = false;
    m_iCTPT=0;
    m_dblSin=0;
    m_dblCos=0;
    m_iTestedPoints=0;
    m_iTestedPoints_bc=0;
    m_iTestedZhouQi=0;
    m_iTestedZhouQi_bc=0;
    m_bSamplingPoints=false;
    m_iShuZiLiangMax = 0;
    m_iShuZiLiangMax_Temp = 0;
    m_dblMaxPoint=0;
    m_dblYouXiaoZhi=0;		// 互感器基波有效值
    m_dblXW=0;				// 互感器所示相位

    m_dblYouXiaoZhi_bc=0;		// 互感器基波有效值
    m_dblXW_bc=0;				// 互感器所示相位
    m_iShuZiLiangMax_bc=0;			// 数字量最大值
    m_iShuZiLiangMax_Temp_bc=0;		// 数字量最大值_临时
    m_dblMaxPoint_bc=0;
    m_iZhouQi=0;
    m_iZhouQi_bc=0;
    m_dblSin_bc=0;
    m_dblCos_bc=0;
    m_dblPL=50;

    m_bRun=false;
    m_isOK=false;
    m_bJQ=false;
    bzxs=0;
    bcxs=0;
    smpcnt=-1;
    mt=0;
    yanshi=0;
    jgMax=0;
    jgMin=0;
    bwAll=0;
    bwLost=0;
    bwError=0;
    bcIsTest=false;
    bzOver=false;
    bcOver=false;
    memset(m_tempBz,0,sizeof(m_tempBz));
    memset(m_tempBc,0,sizeof(m_tempBc));

    sampleArray = &sampleArray1;
    showArray = &sampleArray1;

    memset(sampleArray1,0x00,sizeof(sampleArray1));

    sampleArray_ft3 = &sampleArray1_ft3;
    showArray_ft3 = &sampleArray1_ft3;

    memset(sampleArray1_ft3,0x00,sizeof(sampleArray1_ft3));

    int i = 0;

    for(i = 0; i < 6; i++)
    {
        maxInChannel[i] = 0;
        dblSin_ft3[i] = 0;
        dblCos_ft3[i] = 0;
        ft3Points[i]=0;
        channel_mapping[i]=0;
    }
}

UdpClient::~UdpClient()
{
    this->udpSocket->deleteLater();
    quit();
    wait();
}
void UdpClient::stopRun()
{
    if (m_bRun)
    {
        m_bRun=false;
        this->udpSocket->deleteLater();
        quit();
        wait();
    }
}

void UdpClient::run()
{
    /*
    m_bSamplingPoints=false;
    m_bRun=true;
    udpSocket = new QUdpSocket;
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));
    udpSocket->bind(port);
    exec();
    */
}

void UdpClient::dataReceived()
{
    while (udpSocket->hasPendingDatagrams()) 
    {
	 	QByteArray datagram;
	 	datagram.resize(udpSocket->pendingDatagramSize());
	 	udpSocket->readDatagram(datagram.data(), datagram.size());
        char *ch;
        ch=datagram.data();

        qDebug()<<"udp rcvd length:"<<datagram.size();

        if (datagram.size()==56)
        {
            QString stra(datagram.data());
            if (stra.left(6)=="sanwei")
            {
                m_bSt=true;
                m_bRead=true;
                m_bSamplingPoints=false;
            }
            return;
        }

        if(!m_bRead)
        {
            init();
            m_bJQ=false;
            m_bSt=false;
            return;
        }
   //     if (datagram.size()<1000)
   //         return;
        QString stra(datagram.data());
        if (stra.left(6)!="sanwei")
            return;
//        qDebug()<<datagram.size();
//        qDebug()<<datagram.toHex();

        char flag= ch[6] ;      //标志位

//        qDebug()<<"flag= ch[6],"<<flag;

        if (flag==0x00)
            dataProcess(ch);
        else if (flag==0x1)
            delayProcess(ch);
        else if (flag==0x2)
            dsProcess(ch);
        else if (flag==0x3)
            ssProcess(ch);
        else if (flag=='A')
            muDataProcess(ch);
        else if (flag== 'a')
            packetAnalyzer(ch);

        /*
        m_dblYouXiaoZhi_bc=datagram.size();
        m_dblXW_bc=2.0;
        m_dblPL=50.0;
        emit sigUdpDataIsOK();
        */

    }
}

void UdpClient::packetAnalyzer(char* ch)
{
    packet_error *pkt_error=(packet_error*)ch;

    yanshi=0;
    jgMax=0;
    jgMin=0;
    bwAll=pkt_error->total;
    //bwLost=pkt_error->lost;
    bwLost = 0;
    bwError=pkt_error->disorder;
    m_dblDs=pkt_error->delay/100.0;
    delay_specified = pkt_error->delay_defined;

    qDebug()<<"delay:"<<pkt_error->delay<<pkt_error->delay_defined;

    error1 = pkt_error->error_1;
    error2 = pkt_error->error_2;
    error3 = pkt_error->error_4;
    error4 = pkt_error->error_6;

//    qDebug()<< "new result is coming";
//    qDebug()<< "error1"<<pkt_error->error_1;
//    qDebug()<< "error2"<<pkt_error->error_2;
//    qDebug()<< "error3"<<pkt_error->error_4;
//    qDebug()<< "error4"<<pkt_error->error_6;
//    qDebug()<< "total"<<pkt_error->total;
//    qDebug()<< "lost"<<pkt_error->lost;
//    qDebug()<< "disorder"<<pkt_error->disorder;

    sigUdpDataShow();
}

void UdpClient::dsProcess(char* ch)
{
    ETC_Delay *etc_duishi=(ETC_Delay*)ch;;

    QString str(etc_duishi->de_name);            //内部标识符

    if (str.length()>=6)
    {
        str=str.left(6);
        if (str!="sanwei")
            return;
    }

    m_dblDs=etc_duishi->delay / 10.0;

    qDebug()<<"ds: "<<m_dblDs;

}
void UdpClient::ssProcess(char* ch)
{
    ETC_Duishi *etc_duishi=(ETC_Duishi*)ch;
    QString str(etc_duishi->de_name);            //内部标识符
    if (str.length()>=6)
    {
        str=str.left(6);
        if (str!="sanwei")
            return;
    }
    else
        return;
    m_dblSs=etc_duishi->dTime / 10.0;
 //   qDebug()<<"ss: "<<m_dblSs;
}
void UdpClient::delayProcess(char* ch)
{
    ETC_Delay *etc_delay=(ETC_Delay*)ch;
    QString str(etc_delay->de_name);            //内部标识符
    if (str.length()>=6)
    {
        str=str.left(6);
        if (str!="sanwei")
            return;
    }
    else
        return;
//    jgMin=10000,jgMax=0,jgAvg=0;
    yanshi=etc_delay->delay;
    jgMax=etc_delay->jgMax;
    jgMin=etc_delay->jgMin;
    bwAll=etc_delay->bwAll;
    bwLost=etc_delay->bwLost;
    bwError=etc_delay->bwError;

    sigUdpDataShow();

}

void UdpClient::dataProcess(char * ch)
{
    ETC_S *etc_s=(ETC_S*)(ch);

    QString str(etc_s->de_name);            //内部标识符
    if (str.length()>=6)
    {
        str=str.left(6);
        if (str!="sanwei")
            return;
    }
    else
        return;
    int cnum;
    testFlag=(int)etc_s->ETC_DATA.kind;
    if (testFlag==1)               ///*数据类型  1表示标准通道，2表示被测通道，3表示ft3数据*/
    {
        m_iBzFdbs=(int)etc_s->ETC_DATA.ex[0];
        m_iZhouQi=(int)etc_s->ETC_DATA.cycle;
        bzxs=(double)etc_s->ETC_DATA.xs;
        cnum=(int)etc_s->ETC_DATA.cycle_num;
        m_dblMaxPoint=etc_s->ETC_DATA.sample_rate/50;
        if (smpcnt==-1)
            smpcnt=cnum;
        else
        {
            if (smpcnt==9)
                smpcnt=0;
            else
                smpcnt++;
            if (smpcnt!=cnum)
            {
//                qDebug()<<smpcnt;
                smpcnt=cnum;
            }

        }
    }
    else
    {
        m_iBcFdbs=(int)etc_s->ETC_DATA.ex[0];
        m_iZhouQi_bc=(int)etc_s->ETC_DATA.cycle;
        bcxs=(double)etc_s->ETC_DATA.xs;
        m_dblMaxPoint_bc=etc_s->ETC_DATA.sample_rate/50;
    }

    if(! m_bSamplingPoints && cnum==0)
    {
        m_bSamplingPoints = true;
        m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
    //    parent->jsWc(); //计算误差
        m_iShuZiLiangMax_Temp = 0;
        m_iTestedPoints = 0;
        m_iTestedPoints_bc = 0;
        m_iTestedZhouQi=0;
        m_iTestedZhouQi_bc=0;

        m_iShuZiLiangMax_bc = m_iShuZiLiangMax_Temp_bc;
        m_iShuZiLiangMax_Temp_bc = 0;
    }    
    iShuZiLiang=0;

    if (!m_bJQ)
    {
        m_bJQ=true;
    }
    if (testFlag==0)
    {
        bcOver=true;
        bcIsTest=false;
    }
    else if (testFlag==1)
    {
        for(int i=0;i< m_dblMaxPoint;i++)              //标准数据
        {
            iShuZiLiang =(double)etc_s->ETC_DATA.data[i]*bzxs;     //标准数据
            m_BzArray[m_iTestedPoints]=iShuZiLiang;
            double iTemp = std::fabs(iShuZiLiang);
            if(iTemp > m_iShuZiLiangMax_Temp)
                m_iShuZiLiangMax_Temp = iTemp;
            m_iTestedPoints++;
            if (iSuanFa==0)
            {
                m_dblSin += 2 / (double)m_dblMaxPoint * ((double)iShuZiLiang) * std::sin(2 * PI * (m_iTestedPoints-1) / m_dblMaxPoint);
                m_dblCos += 2 / (double)m_dblMaxPoint * ((double)iShuZiLiang) * std::cos(2 * PI * (m_iTestedPoints-1) / m_dblMaxPoint);
            }
        }
  //  qDebug()<<"bz:"<<(double)etc_s->ETC_DATA.data[80]*bzxs;

        if(m_iTestedZhouQi < m_iZhouQi -1)//etc_s->ETC_DATA.cycle
        {
                m_iTestedZhouQi +=1;
        }
        else
        {
        //    qDebug()<<etc_s->ETC_DATA.cycle_num;
            m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
            memcpy(m_tempBz,m_BzArray,sizeof(m_BzArray));
            if (iSuanFa==0)
            {
                m_dblYouXiaoZhi = std::sqrt(m_dblSin * m_dblSin + m_dblCos * m_dblCos)
                                            / std::sqrt(2) / (double)m_iZhouQi;
                m_dblXW = GetXiangJiao(m_dblSin, m_dblCos) * 60;
                if (!bcIsTest)
                  emit sigUdpDataIsOK();
            }
            else if (iSuanFa==2)
            {
                bzOver=true;
            }

            m_isOK=true;
            m_dblSin=0;
            m_dblCos=0;
            m_iTestedZhouQi=0;
            m_bSamplingPoints=false;

        }
    }
    else if ((testFlag==2)||(testFlag==3))
    {
        bcIsTest=true;
        for(int i=0;i< m_dblMaxPoint_bc;i++)           ////被测数据
        {
            iShuZiLiang =(double)etc_s->ETC_DATA.data[i]*bcxs;
            m_BcArray[m_iTestedPoints_bc]=iShuZiLiang;
            double iTemp = std::fabs(iShuZiLiang);
            if(iTemp > m_iShuZiLiangMax_Temp_bc)
                m_iShuZiLiangMax_Temp_bc = iTemp;
            m_iTestedPoints_bc++;
            if (iSuanFa==0)
            {
                m_dblSin_bc += 2 / (double)m_dblMaxPoint_bc * ((double)iShuZiLiang) * std::sin(2 * PI * (m_iTestedPoints_bc-1) / m_dblMaxPoint_bc);
                m_dblCos_bc += 2 / (double)m_dblMaxPoint_bc * ((double)iShuZiLiang) * std::cos(2 * PI * (m_iTestedPoints_bc-1) / m_dblMaxPoint_bc);
            }
        //    qDebug()<<(double)etc_s->ETC_DATA.data[249]*bcxs;
        }

        if(m_iTestedZhouQi_bc < m_iZhouQi_bc - 1)
        {
                m_iTestedZhouQi_bc +=1;
/*
                if (m_iTestedZhouQi_bc==1)
                {
                    m_dblYouXiaoZhi_bc = std::sqrt(m_dblSin_bc * m_dblSin_bc + m_dblCos_bc * m_dblCos_bc)
                                                / std::sqrt(2) ;
                    qDebug()<<"bcyxz:"<<m_dblYouXiaoZhi_bc<<" "<<bcxs<<" "<<m_dblSin_bc<<" "<<m_dblCos_bc;
                }*/

        }
        else
        {
            if(testFlag==3)
                ft3JianXi(etc_s->ETC_DATA.ft3_config,(int)etc_s->ETC_DATA.ft3_freq);
            m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
             //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
            memcpy(m_tempBc,m_BcArray,sizeof(m_BcArray));
                if (iSuanFa==0)
                {
                    m_dblYouXiaoZhi_bc = std::sqrt(m_dblSin_bc * m_dblSin_bc + m_dblCos_bc * m_dblCos_bc)
                                                / std::sqrt(2) / (double)m_iZhouQi_bc;
                    m_dblXW_bc = GetXiangJiao(m_dblSin_bc, m_dblCos_bc) * 60;
               //     qDebug()<<"bcyxz:"<<m_dblYouXiaoZhi_bc;
                    emit sigUdpDataIsOK();
                }
                else if (iSuanFa==2)
                {
                    bcOver=true;
               //     memcpy(m_tempBc,m_BcArray,sizeof(m_BcArray));
                }
            //        harmonic(m_BcArray,1,m_dblMaxPoint_bc*m_iZhouQi_bc,m_dblMaxPoint_bc*50,1) ;
            m_isOK=true;
            m_dblSin_bc=0;
            m_dblCos_bc=0;
        //    emit sigUdpDataIsOK();
         //   m_iTestedZhouQi_bc=0;
            m_bSamplingPoints=false;
            m_iTestedPoints_bc = 0;
            m_iTestedZhouQi_bc=0;
        }
    }
    if ((bzOver) && (bcOver))
    {
        bcOver=false;
        bzOver=false;
        harmonic(m_tempBz,1,m_dblMaxPoint_bc*m_iZhouQi,m_dblMaxPoint*50,0);
        if (bcIsTest)
            harmonic(m_tempBc,1,m_dblMaxPoint_bc*m_iZhouQi_bc,m_dblMaxPoint_bc*50,1);
        emit sigUdpDataIsOK();

    }
}

void UdpClient::UdpSend(QString s)
{
   /*
    QString s("hello");
    QByteArray cstr = s.toLatin1();
    */
    QByteArray datagram = s.toLatin1();
    udpSocket->writeDatagram(datagram.data(),datagram.size(), QHostAddress::Broadcast,port);
}
void UdpClient::UdpSendByte(char *ch,int size)
{
    QHostAddress hostaddr;
   // hostaddr= new QHostAddress("192.168.1.88");//主机IP
    hostaddr.setAddress("192.168.1.88");   //主机IP
  //  for(int i=0;i<3;i++)
        udpSocket->writeDatagram(ch,size,hostaddr,port);//QHostAddress::Broadcast,hostaddr
}

void UdpClient::UdpSendCmd(char *ch,int size)
{
    QHostAddress hostaddr;
    hostaddr.setAddress("127.0.0.1");   //主机IP

    udpSocket->writeDatagram(ch,size,hostaddr,2000);//QHostAddress::Broadcast,hostaddr
}

void UdpClient::harmonic(double *s,int M,int len,int fs,int flag)   //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
{
        int p,n,j,k;
        double a,b;
        int f0;
        double y,y2,maxu;
        long k0;

        double A[40];
        double B[40];
        double C[40];

        f0=50;
        double r[len];
        memset(r,0,len);
        for(p=0;p<len;p++)
        {
            r[p]=s[p] *(0.42-0.5*std::cos(2*PI*p/len)+0.08*std::cos(4*PI*p/len));
        //    qDebug()<<flag<<" "<<p<<" "<<s[p];
        }

        int tm=len/(fs/50)+4;//len/(fs/50)+4;
     //   int tm=len;
        double L[tm];
        double T[tm];
        for(p=0;p<tm;p++)
        {
            L[p]=0;
            T[p]=0;
                for(n=0;n<len;n++)
                {
                    T[p]=T[p]+r[n]*std::cos(2*PI*p*n/len);
                    L[p]=L[p]-r[n]*std::sin(2*PI*p*n/len);
                }
        }
        double u[len];
        for(p=0;p<len;p++)
        {
            u[p]=std::sqrt(L[p]*L[p]+T[p]*T[p]);
        }

        for(p=0;p<M;p++)
        {
            k0=std::ceil(f0*(p+1)*len/fs)+1;
                maxu=u[k0];
                k=k0;
                for(j=k0-3;j<k0+3;j++)
                {
                        if(maxu<u[j])
                        {
                                maxu=u[j];
                                k=j;
                        }
                }
                y=u[k];
                y2=u[k+1];
                b=(y2-y)/(y2+y);
                a=1.96043163*b+0.15277325*std::pow(b,3)+0.07425838*std::pow(b,5)+0.049985*std::pow(b,7);
                A[p]=(k+1+a-0.5)*fs/len;
            B[p]=(y+y2)*(2.70205774+1.071151*std::pow(a,2)+0.23361915*std::pow(a,4)+0.04017668*std::pow(a,6))/len;
            if(T[k]>0 && L[k]>0)
                C[p]=std::atan(L[k]/T[k])-PI*(a+0.5);
                else if(T[k]>0 && L[k]<0)
                    C[p]=std::atan(L[k]/T[k])-PI*(a+0.5);
                else  if(T[k]<0 && L[k]>0)
                    C[p]=std::atan(L[k]/T[k])+PI-PI*(a+0.5);
                else if(T[k]<0 && L[k]<0)
                    C[p]=std::atan(L[k]/T[k])-PI-PI*(a+0.5);
                else if(T[k]==0)
                {
                        if(L[k]>0)
                                C[p]=PI/2-PI*(a+0.5);
                        else if(L[k]<0)
                                C[p]=-PI/2-PI*(a+0.5);
                        else if(L[p]==0)
                                C[p]=-PI*(a+0.5);
                }
                else if(L[k]==0)
                {
                        if(T[k]>0)
                                C[p]=-PI*(a+0.5);
                        else if(T[k]<0)
                                C[p]=PI-PI*(a+0.5);
                }
                if(C[p]<-PI)
                        C[p+1]=C[p]+2*PI;
            if(C[p]>PI)
                C[p+1]=C[p]-2*PI;
        }
        C[0]=C[0]+PI/2;
        if (flag==0)                //标准时
        {
            m_dblYouXiaoZhi=B[0]/1.4142135623;//m_dblFuZhi
     //   m_dblYouXiaoZhi=B[0]/1.4142135623/2000;
            m_dblXW=C[0]*180*60/PI;
            if (m_dblXW<0)
                m_dblXW+=360*60;
                //C[0]初相角  B[0]/1.4142135623 有效值
       //     qDebug()<<m_dblYouXiaoZhi;
             m_dblPL=A[0];
        }
        else                        //被测时
        {
            /* 积分算法
            double temp_yxz=0;
            for(int i=0;i<len;i++)
                temp_yxz +=s[i]*s[i];
            temp_yxz /=len;
            temp_yxz =std::sqrt(temp_yxz);

            m_dblYouXiaoZhi_bc=temp_yxz;
            */
            m_dblYouXiaoZhi_bc=B[0]/1.4142135623;
            m_dblXW_bc=C[0]*180*60/PI;
            if (m_dblXW_bc<0)
                m_dblXW_bc+=360*60;
            if (testFlag==3)         //ft3时
            {
                m_dblXW_bc -=(int)etc_ft3.EDYS *1.08;
            }
        }

}
void UdpClient::ft3JianXi(unsigned short data[10],int freq)
{
    /*
     ft3_config[0]:数据集长度;
     ft3_config[1]:LNName(高8位) & DataSetName (低8位)
     ft3_config[2]:LDName
     ft3_config[3]:额定相电流
     ft3_config[4]:额定中性点电流
     ft3_config[5]:额定相电压
     ft3_config[6]:额定延时时间
     ft3_config[7]:状态字1
     ft3_config[8]:状态字2
     ft3_config[9]:暂时无用
    */
    etc_ft3.LNName=data[1]>>8;
    etc_ft3.DataSetName=data[1]&0X00FF;
    etc_ft3.LDName=data[2];
    etc_ft3.EDXDL=data[3];
    etc_ft3.EDZXDL=data[4];
    etc_ft3.EDXDY=data[5];
    etc_ft3.EDYS=data[6];
    delay_in_packet = data[6];
    etc_ft3.statusWord1=data[7];
    etc_ft3.statusWord2=data[8];
    etc_ft3.RangeFlag=(0x01<<13) & etc_ft3.statusWord1;
    etc_ft3.freq=freq;
  //  qDebug()<<etc_ft3.RangeFlag;
  //  (0x01<<5) & ((etc_ft3.statusWord1& 0XF0)>>8);
}
int UdpClient::getFt3Xs()
{
    double tempfz=1;
   // if (testFlag==3)         //ft3时
   // {
        if (m_iCTPT==0)
        {
            if (m_iFT3lx==1)            //保护用
            {
                if ((int)etc_ft3.RangeFlag>0)
                    tempfz=231;             //0x00E7
                else
                    tempfz=463;             //0x01CF
            }
            else                            //测量用
            {
                tempfz=11585;               //0X2D41
            }
        }
        else
        {
            tempfz=11585;           //0X2D41
        }
   // }
    return tempfz;
}

void UdpClient::setFt3Channel(int index, int channel)
{
    channel_mapping[index] = channel;
}

void UdpClient::muDataProcess(char * ch)
{
    static double mxFt3Sample_tmp = 0;
    static double dblSampleMax_tmp = 0;
    static double maxInChannel_tmp[6] = {0};
    static double maxFt3_inChannel_tmp[6] ={0};

    MUT_S *mut_s = (MUT_S*)(ch);

    if(isFt3 && ( mut_s->MUT_Data.kind == 3)) //FT3
    {
        //qDebug()<< "ft3 data is found!";
        m_iZhouQi_bc = (int)mut_s->MUT_Data.cycle;

        m_dblMaxPoint_bc = mut_s->MUT_Data.sample_rate/50;

        int cnum_ft3 = mut_s->MUT_Data.cycle_num;

        int num_channel = mut_s->MUT_Data.ft3_chnl;

        int channel_index = 0;

        for(channel_index = 0; channel_index < 6; channel_index++)
        {
            if(channel_mapping[channel_index] + 1 == num_channel)
            {
                // samples for one channel comes continoursly
                if( ft3Points[channel_index] < m_dblMaxPoint_bc * m_iZhouQi_bc)
                {
                    break;
                }
            }
        }

        //qDebug()<<"channel="<<num_channel<<", channel_index="<<channel_index<<",cnum="<<cnum_ft3;

        if (channel_index == 6)
        {
            static bool isShown = false;

            if(!isShown)
            {
                qDebug()<<"FT3 通道号与设置不匹配, 或 FT3 未接入！";
                isShown = true;
            }

            return;
        }

        if(channel_index < 3)
        {
            bcxs = ft3_factor_voltage; // rating for measure
        }
        else
        {
            bcxs = ft3_factor_current;
        }

        qDebug()<<"max point"<<m_dblMaxPoint_bc;

        ft3JianXi( mut_s->MUT_Data.ft3_config,  mut_s->MUT_Data.ft3_freq);

        for(int j = 0; j < m_dblMaxPoint_bc; j++)
        {
            int sample_index = (cnum_ft3 % 6) * m_dblMaxPoint_bc + j;

            iShuZiLiang = mut_s->MUT_Data.data[j] * bcxs + 0.000000000001;

            //qDebug()<<"samples"<< iShuZiLiang;
            //qDebug()<<channel_index<<", dblSin_ft3"<<dblSin_ft3[channel_index];

            dblSin_ft3[channel_index] += 2.0 / 80.0 * ((double)iShuZiLiang) * std::sin(2 * PI * (sample_index%80) / 80);
            dblCos_ft3[channel_index] += 2.0 / 80.0 * ((double)iShuZiLiang) * std::cos(2 * PI * (sample_index%80) / 80);

            //qDebug()<<channel_index<<", new dblSin_ft3"<<sample_index<<dblSin_ft3[channel_index];

            (*sampleArray_ft3)[channel_index][sample_index] = iShuZiLiang;

            double iTemp = std::fabs(iShuZiLiang);

            if(iTemp > mxFt3Sample_tmp)
                mxFt3Sample_tmp = iTemp;

            if(iTemp > maxFt3_inChannel_tmp[channel_index])
                maxFt3_inChannel_tmp[channel_index] = iTemp;

            ft3Points[channel_index]++;

           // qDebug()<<"ft3 sample"<<channel_index<< iShuZiLiang;
        }

        if(ft3Points[channel_index] == m_dblMaxPoint_bc * 6)
        {
            dblYxzUdp_ft3[channel_index] = std::sqrt(dblSin_ft3[channel_index] * dblSin_ft3[channel_index]
                           + dblCos_ft3[channel_index] * dblCos_ft3[channel_index]) / std::sqrt(2)/6;
            dblXwUdp_ft3[channel_index] = GetXiangJiao(dblSin_ft3[channel_index], dblCos_ft3[channel_index]) * 60;

            if(dblYxzUdp_ft3[channel_index] < 0.00000001)
            {
                dblYxzUdp_ft3[channel_index] = 0;
                dblXwUdp_ft3[channel_index] = 0;
            }

            qDebug()<<"I get all samples for "<<channel_index
                   <<"yxz="<<dblYxzUdp_ft3[channel_index]<<"xw="<<dblXwUdp_ft3[channel_index];

            dblSin_ft3[channel_index] = 0;
            dblCos_ft3[channel_index] = 0;
        }

        if( cnum_ft3 == 35) // now 6*6 = 36 cycles
        {
            if(sampleArray_ft3 == &sampleArray1_ft3)
            {
                sampleArray_ft3 = &sampleArray2_ft3;
                showArray_ft3 = &sampleArray1_ft3;

                qDebug() << "eggs has been in bucket: sampleArray1_ft3";
            }
            else
            {
                sampleArray_ft3 = &sampleArray1_ft3;
                showArray_ft3 = &sampleArray2_ft3;

                qDebug() << "eggs has been in bucket: sampleArray2_ft3";
            }

            mxFt3Sample = mxFt3Sample_tmp;
            mxFt3Sample_tmp = 0;

            memcpy(maxFt3_inChannel, maxFt3_inChannel_tmp,sizeof(maxFt3_inChannel_tmp));
            memset(maxFt3_inChannel_tmp, 0x00,sizeof(maxFt3_inChannel_tmp));

            ft3Points[0] = ft3Points[1] =ft3Points[2] =ft3Points[3] =ft3Points[4] =ft3Points[5] = 0;

            emit ft3IsReady();
        }
    }
    else
    {
        m_iBzFdbs = (int)mut_s->MUT_Data.ex[0];

        double hwGain = (double)mut_s->MUT_Data.xs;
        m_iZhouQi = (int)mut_s->MUT_Data.cycle;
        m_dblMaxPoint = mut_s->MUT_Data.sample_rate/50;

        testFlag = (int)mut_s->MUT_Data.ex[2] - 1; //0-Ua,1-Ub,2-Uc,3-Ia,4-Ib,5-Ic

        int cnum=(int)mut_s->MUT_Data.cycle_num;

        if(cnum == 0)
        {
            dblSampleMax_tmp == 0;
        }

        for(int i=0; i < 240 ; i++)   //240 points in a packet
        {
            int pos = 0;

            pos = (cnum % 4) * 240 + i;

            iShuZiLiang =(double)mut_s->MUT_Data.data[i] * hwGain + 0.0000000000000001;

            if(((testFlag == 0)||(testFlag == 1)||(testFlag == 2) )&& (pos%80 == 0))
            {
                qDebug()<<"udp::sample----MUT_Data.ex[2] ="<<testFlag+1<<",pos="<<pos<<",sampleValue="<<iShuZiLiang;
            }

            if(pos <= 799)
            {
#if 0
                dblSin[testFlag] += 2 / 80.0 * ((double)iShuZiLiang) * std::sin(2 * PI * (pos%80) / 80);
                dblCos[testFlag] += 2 / 80.0 * ((double)iShuZiLiang) * std::cos(2 * PI * (pos%80) / 80);
#endif
                (*sampleArray)[testFlag][pos] = iShuZiLiang;

                double iTemp = std::fabs(iShuZiLiang);

                if(iTemp > dblSampleMax_tmp)
                    dblSampleMax_tmp = iTemp;

                if(iTemp > maxInChannel_tmp[testFlag])
                    maxInChannel_tmp[testFlag] = iTemp;
            }
            else if(pos == 800)
            {
#if 0
                dblYxzUdp[testFlag] = 10.0 * std::sqrt(dblSin[testFlag] * dblSin[testFlag] + dblCos[testFlag] * dblCos[testFlag])
                        / std::sqrt(2) / maxValueStd[testFlag];
                dblXwUdp[testFlag] = GetXiangJiao(dblSin[testFlag], dblCos[testFlag]) * 60;

                dblSin[testFlag] = 0;
                dblCos[testFlag] = 0;
#else
                dft_14((*sampleArray)[testFlag], 1, 800, 4000);

                dblYxzUdp[testFlag] = 100.0 * rms_tmp / maxValueStd[testFlag];
                dblXwUdp[testFlag] = phase_tmp;
#endif
    //            if (m_iBzFdbs == 1000)
    //                dblXwUdp[testFlag] +=139;
    //            else if (m_iBzFdbs == 100)
    //                dblXwUdp[testFlag] +=14.5;
    //            else if (m_iBzFdbs == 10)
    //                dblXwUdp[testFlag] +=1.92;

                //qDebug()<<"udp::MUT_Data.ex[2] ="<<testFlag+1<<",yxz="<<dblYxzUdp[testFlag]<<",xw="<<dblXwUdp[testFlag];
            }
            else if(pos > 799)
            {
                continue;
            }
        }

        qDebug()<<"cnum="<<cnum;

        if(cnum == 23)
        {
            if(sampleArray == &sampleArray1)
            {
                sampleArray = &sampleArray2;
                showArray = &sampleArray1;

                qDebug() << "eggs has been in bucket sampleArray1";
            }
            else
            {
                sampleArray = &sampleArray1;
                showArray = &sampleArray2;

                qDebug() << "eggs has been in bucket :sampleArray2";
            }

            dblSampleMax_udp = dblSampleMax_tmp;
            dblSampleMax_tmp = 0;

            int iChannel;
            for(iChannel = 0; iChannel < 6; iChannel++)
            {
                maxInChannel[iChannel] = maxInChannel_tmp[iChannel]/maxValueStd[iChannel] * 141.421;
                maxInChannel_tmp[iChannel] = 0;
            }

            harmonic((*showArray)[0],800,4000,0);

            emit sigUdpMutIsReady();
        }
    }
}

void UdpClient::harmonic(double *s,int len,int fs,int flag)   //reload, to get freq of Ua only
{
        int p,n,j,k;
        double a,b;
        int f0;
        double y,y2,maxu;
        long k0;

        double A[40];
        double B[40];
        double C[40];

        int M = 1;

        f0=50;
        double r[len];
        memset(r,0,len);
        for(p=0;p<len;p++)
        {
            // r[p]=s[p] *(0.42-0.5*std::cos(2*PI*p/len)+0.08*std::cos(4*PI*p/len));

            r[p]=s[p] *(0.3125-0.46875*std::cos(2*PI*p/len)+0.1875*std::cos(4*PI*p/len)-0.03125*std::cos(6*PI*p/len));//FDMS_1 Window
        }

        // int tm=len/(fs/50)+4;//len/(fs/50)+4;
        int tm=len*M*50/fs+4;//M=1,tm=14;M=40,tm=404;
     //   int tm=len;
        double L[tm];
        double T[tm];
        for(p=0;p<tm;p++)
        {
            L[p]=0;
            T[p]=0;

            for(n=0;n<len;n++)
            {
                T[p]=T[p]+r[n]*std::cos(2*PI*p*n/len);
                L[p]=L[p]+r[n]*std::sin(2*PI*p*n/len);
            }
        }
        double u[len];
        for(p=0;p<len;p++)
        {
            u[p]=std::sqrt(L[p]*L[p]+T[p]*T[p]);
        }

        for(p=0;p<M;p++)
        {
            k0=std::ceil(f0*(p+1)*len/fs);
            maxu=u[k0];
            k=k0;
            for(j=k0-3;j<k0+3;j++)
            {
                    if(maxu<u[j])
                    {
                            maxu=u[j];//first high of freq spectrum
                            k=j;
                    }
            }

            if(u[k-1]>u[k+1])  k=k-1;//second high of freq	spectrum

            y=u[k];
            y2=u[k+1];
            b=(y2-y)/(y2+y);
            a=3.5*b;

            A[p]=(k+a+0.5)*fs/len;//freq of signal

            B[p]=(y+y2)*(3.43612+0.85434*std::pow(a,2)+0.11871*std::pow(a,4))/len;//RMS of signal

            if(T[k]>0)
                C[p]=std::acos(L[k]/u[k])-(a+0.5)*PI;//phase of angel,range of angel is 0-2*PI
            else if(T[k]<0)
                C[p]=2*PI-std::acos(L[k]/u[k])-(a+0.5)*PI;
            else if(T[k]==0)
            {
                 if(L[k]>=0)   C[p]=-(a+0.5)*PI;
                 else    C[p]=PI-(a+0.5)*PI;
            }
        }

        m_dblPL=A[0];

        qDebug()<<"get freq of Ua"<<m_dblPL;
}


void UdpClient::dft_14(double *samples,int M,int dft_N,int fs)   //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
{
    int peak,n,k;
    double magic;
    double y,y2,maxu;

    int f0=50;
    long k0;

    double windowed_samples[dft_N];
    memset(windowed_samples,0,dft_N);

    for(n=0;n<dft_N;n++)
    {
        windowed_samples[n]=samples[n] *(0.3125-0.46875*std::cos(2*PI*n/dft_N)+0.1875*std::cos(4*PI*n/dft_N)-0.03125*std::cos(6*PI*n/dft_N));//FDMS_1 Window
    }

    int maxK=14;

    double Imag[maxK];
    double Real[maxK];
    for(k = 0;k < maxK;k++)
    {
        Imag[k]=0;
        Real[k]=0;

        for(n=0;n<dft_N;n++)
        {
            Real[k] = Real[k] + windowed_samples[n] * std::cos(2*PI*k*n/dft_N);
            Imag[k] = Imag[k] + windowed_samples[n] * std::sin(2*PI*k*n/dft_N);
        }
    }

    double X_abs[maxK];
    for(k=0;k<maxK;k++)
    {
        X_abs[k]=std::sqrt(Imag[k]*Imag[k]+Real[k]*Real[k]);
    }

    k0=std::ceil(f0*M*dft_N/fs);
    maxu=X_abs[k0];

    peak=k0;

    for(k=k0-3;k<k0+3;k++)
    {
        if(maxu<X_abs[k])
        {
            maxu=X_abs[k];//first high of freq spectrum
            peak=k;
        }
    }

    if(X_abs[peak-1] > X_abs[peak+1])  peak = peak - 1;

    y=X_abs[peak];
    y2=X_abs[peak+1];

    magic = 3.5*(y2-y)/(y2+y);

    freq_tmp = (peak+magic+0.5)*fs/dft_N;//freq of signal

    rms_tmp = (y+y2)*(3.43612+0.85434*std::pow(magic,2)+0.11871*std::pow(magic,4))/dft_N/1.4142135623;

    if(Real[peak]>0)
        phase_tmp=std::acos(Imag[peak]/X_abs[peak])-(magic+0.5)*PI;//phase of angel,range of angel is 0-2*PI
    else if(Real[peak]<0)
        phase_tmp=2*PI-std::acos(Imag[peak]/X_abs[peak])-(magic+0.5)*PI;
    else if(Real[peak]==0)
    {
        if(Imag[peak]>=0)   phase_tmp=-(magic+0.5)*PI;
        else    phase_tmp=PI-(magic+0.5)*PI;
    }

    if ((phase_tmp *= 180*60/PI) < 0) phase_tmp += 360*60;

    qDebug()<<"udp,dft_14:"<<rms_tmp<<phase_tmp<<freq_tmp;
}
